package com.gw.vip.center.auth;

import com.gw.vip.center.constant.VipCenterConstants;
import com.gw.vip.center.util.RedisUtil;
import com.gw.vip.common.exception.ExceptionEnums;
import com.gw.vip.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @description 校验邮件验证码
 * @author GW
 * @since 2022-04-17
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CheckMailAuthCodeAspect {

    private final RedisUtil redisUtil;

    @Pointcut("@annotation(com.gw.vip.center.auth.CheckMailAuthCode)")
    public void CheckMailAuthCode(){};

    @Around("CheckMailAuthCode()")
    public Object checkAuth(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        if (args.length<1){
            log.error("校验邮件验证码参数错误！");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS, "校验邮件验证码参数错误!");
        }
        CheckMailAuthCodeBo bo = new CheckMailAuthCodeBo();
        BeanUtils.copyProperties(args[0], bo);
        log.info("邮件验证码校验参数{}", bo);

        if (StringUtils.isBlank(bo.getMailAddress())){
            log.error("校验邮件验证码参数错误！");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS, "校验邮件验证码参数错误!");
        }

        if (StringUtils.isBlank(bo.getMailAuthCode())){
            log.error("校验邮件验证码参数错误！");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS, "校验邮件验证码参数错误!");
        }

        String mailAuthCodeRedis = redisUtil.get(VipCenterConstants.MAIL_AUTH_CODE+":"+bo.getMailAddress());
        if (StringUtils.isBlank(mailAuthCodeRedis)){
            log.error("请获取验证码！邮箱【{}】", bo.getMailAddress());
            throw new ServiceException(ExceptionEnums.NEED_AUTH_CODE);
        }

        if (!mailAuthCodeRedis.equals(bo.getMailAuthCode())){
            log.error("验证码错误！邮箱【{}】,验证码【{}】,上送验证码【{}】", bo.getMailAddress(), mailAuthCodeRedis, bo.getMailAuthCode());
            throw new ServiceException(ExceptionEnums.ERROR_AUTH_CODE);
        }

        return point.proceed();
    }
}
